package com.tony.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {


	public static void zip(OutputStream os, String sourceFileName) throws Exception {
		ZipOutputStream out = new ZipOutputStream(os);
		BufferedOutputStream bos = new BufferedOutputStream(out);

		try {
			File sourceFile = new File(sourceFileName);
			compress(out, bos, sourceFile, sourceFile.getName());
		} finally {
			try {
				bos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				bos.flush();
				bos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	

	public static void compress(ZipOutputStream out, BufferedOutputStream bos, File sourceFile, String base)
			throws Exception {
		if (sourceFile.isDirectory()) {

			File[] flist = sourceFile.listFiles();

			if (flist.length == 0) {
				System.out.println(base + "/");
				out.putNextEntry(new ZipEntry(base + "/"));
			} else {
				for (int i = 0; i < flist.length; i++) {
					compress(out, bos, flist[i], base + "/" + flist[i].getName());
				}
			}
		} else {
			out.putNextEntry(new ZipEntry(base));
			FileInputStream fos = new FileInputStream(sourceFile);
			BufferedInputStream bis = new BufferedInputStream(fos);

			int tag;
			while ((tag = bis.read()) != -1) {
				bos.write(tag);
				bos.flush();
			}
			bis.close();
			fos.close();
		}
	}
}
